﻿using HZY.Framework.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using YR.Framework.Core;
using YR.Framework.Freesql;

namespace SingleWpfProject
{
    /// <summary>
    /// 模块初始化类
    /// </summary>
    internal class ModuleInit : IModule
    {
        public void InitService(ServiceCollection services)
        {
            services.AddDependencyInjection(new List<Assembly>(){
                typeof(ModuleInit).Assembly
            });

#if DEBUG
            InitService initService = new InitService();

            // 开发模式自动同步数据库，某一个程序集下的实体会自动同步到数据库
            var entityTypes = Assembly.GetAssembly(typeof(InitEntity)).GetExportedTypes()
                                .Where(NeedSyncEntity)
                                .Select(t => t).ToArray();
            initService.Db.CodeFirst.SyncStructure(entityTypes);
#endif
        }

        /// <summary>
        /// 需要同步的实体判断方法
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool NeedSyncEntity(Type type)
        {
            bool isGenericType = type.BaseType.IsGenericType;
            if (!isGenericType) 
                return false;

            string typeName = type.Name;
            foreach (var item in Consts.EntityEndWith)
            {
                if (typeName.EndsWith(item))
                    return true;
            }
            return false;
        }
    }


    /// <summary>
    /// 初始化实体-标记类-用于扫描实体
    /// </summary>
    internal class InitEntity : BaseEntity<long>
    {

    }

    /// <summary>
    /// 初始化服务
    /// </summary>
    internal class InitService : BaseService<InitEntity, long>
    {
        public InitService() : base(Consts.DbKey)
        {

        }
    }
}
